<template>
  <div> 
    <el-table
      v-table-style
      ref="materialTable"
      header-row-class-name="base-table-header-v3"
      row-class-name="base-table-row-v3"
      :data="data"
      :border="border"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="48"></el-table-column>
      <el-table-column fixed='left' type="index" width="50" :label="$t('common.base.SN')" />
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.fieldName}_${index}_${uuid()}`"
        :label="column.displayName"
        :prop="column.fieldName"
        show-overflow-tooltip
        :width="column.width"
        :min-width="column.minWidth || '110px'"
        :fixed="column.fixed"
      >
        <template slot-scope="scope">
          <template v-if="column.fieldName === 'name'">
            {{ scope.row.materialName }}
          </template>
          <template v-else-if="column.fieldName === 'sn'">
            {{ scope.row.materialSn }}
          </template>
          <!-- 结算规则 S -->
          <template v-else-if="column.fieldName === 'settlementRules'">
            <el-select v-model="scope.row.settlementRulesId" :placeholder="$t('zhongqi.tipList.tips1')" @change="handleChangeRule(scope.row)">
              <el-option
                v-for="item in ruleOptions"
                :key="item.value"
                :label="item.ruleName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
          <!-- 结算规则 E -->

          <!-- start 终端销售价 -->
          <template v-else-if="column.fieldName === 'salePrice'">
            <!-- TODO 国际化灰度开启 -->
            {{ scope.row | fmt_salePrice_currency }}
          </template>
          <!-- end 申请数量 -->

          <!-- start 申请数量 -->
          <template v-else-if="column.fieldName === 'number'">
            <el-input-number v-model="scope.row.number" step-strictly controls-position="right" :min="0" :max="scope.row.availableNum">
            </el-input-number>
          </template>
          <!-- end 申请数量 -->
          <!-- start 物料类型 -->
          <template v-else-if="column.fieldName === 'property'">
            {{ scope.row[column.fieldName] ? 
              $t(`task.${scope.row[column.fieldName]}`) : 
              scope.row[column.fieldName] 
            }}
          </template>
          <!-- end 物料类型 -->

          <!-- start 富文本 -->
          <template v-else-if="column.formType === 'richtext'">
            <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
              <span v-if="scope.row && scope.row.attribute && scope.row.attribute[column.fieldName]">{{$t('common.base.view')}}</span>
            </div>
          </template>
          <!-- end 富文本 -->

          <!-- start 配件结算方式 -->
          <template v-else-if="column.fieldName === 'settleType'">
            <el-select v-model="scope.row.settleType">
              <el-option
                v-for="option in settleTypeOptions"
                :key="option"
                :label="option"
                :value="option"
              ></el-option>
            </el-select>
          </template>
          <!-- end 配件结算方式 -->
          
          <template v-else>{{ $formatFormField(column, scope.row) }}</template>
        </template>
      </el-table-column>

    </el-table>

    <!-- 富文本弹窗 -->
    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
  </div>
</template>

<script>
import { getRootWindow } from '@src/util/dom';
import { GrayFunctionEnum } from '@model/grayFunction'
export default {
  name: 'material-table-new-version',
  props: {
    field: {
      type: Object,
      default: () => ({})
    },
    data: {
      type: Array,
      default: () => ([])
    },
    border: {
      type: Boolean,
      default: false
    },
    // 结算规则下拉数据
    ruleOptions: {
      type: Array,
      default: () => ([])
    },
    // 规则灰度
    isShowSettlementRules: {
      type: Boolean,
      default: false
    },
    isShowSettleType: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      multipleSelection: []
    }
  },
  computed: {
    batchSelectGray () {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.[GrayFunctionEnum.BATCH_PERIOD] ?? true // 批次号灰度
    },
    // 关联物料字段
    relationMaterialFields() {
      let newFields = (this.field?.setting?.materialFields || []).map(item => {
        return {
          ...item,
          displayName: item?.displayName || item?.label,
          fieldName: item?.field || item?.fieldName
        }
      })
      return newFields;
    },
    columns(){
      let list = [
        ...this.relationMaterialFields,
        // {
        //   displayName: this.$t('common.form.preview.materialReturn.tableLabel14'),
        //   fieldName: 'batchNumber'
        // }, 
        {
          displayName: this.$t('common.form.preview.materialReturn.label1'),
          fieldName: 'warehouseName',
          minWidth: '110px',
        }, 
        {
          displayName: this.$t('common.form.preview.materialReturn.label2'),
          fieldName: 'warehousePositionName',
          minWidth: '110px',
        },  
        {
          displayName: this.$t('common.zhongqi.title1'),
          fieldName: 'settlementRules',
          minWidth: '110px',
        },
        {
          displayName: this.$t('common.form.preview.materialVerifyEliminate.settleType'),
          fieldName: 'settleType',
          minWidth: '110px'
        },
        {
          displayName: this.$t('common.form.preview.materialVerifyEliminate.availableNum'),
          fieldName: 'availableNum',
          minWidth: '110px'
        }, 
        
        {
          displayName: this.$t('common.form.preview.materialVerifyEliminate.applyNum'),
          fieldName: 'number',
          minWidth: '110px',
          fixed:'right'
        }, 
      ]

      // 完成回执-物料核销 是否隐藏终端销售价
      if(!this.serviceProviderShowPrice) {
        list = list.filter(field => field.fieldName !== 'salePrice')
      }

      // 结算规则
      if (!this.isShowSettlementRules) {
        list = list.filter(field => field.fieldName !== 'settlementRules')
      }

      if(!this.batchSelectGray) {
        list = list.filter(item => item.fieldName !== 'batchNumber')
      }

      // 未开启 配件结算方式
      if (!this.isShowSettleType) {
        list = list.filter(item => item.fieldName !== 'settleType')
      }

      return list
    },
    
    // 是否开放服务商查看服务项目和物料的价格信息
    serviceProviderShowPrice() {
      try {
        const RootWindow = getRootWindow(window);
        const InitData = RootWindow._init ? JSON.parse(RootWindow._init) : {};
        return InitData.serviceProviderShowPrice ?? true;
      } catch (error) {
        return true;
      }
    },
    // 配件结算方式选项
    settleTypeOptions() {
      return this.field?.setting?.settleTypeOptions || []
    },
  },
  methods: {
    outsideGetTableData() {
      return this.data || []
    },
    outsideSetTableData() {
      this.multipleSelection = [];
      this.$refs?.materialTable?.clearSelection();
    },
    handleSelectionChange(value) {
      this.multipleSelection = value
    },
    // change 规则
    handleChangeRule(row) {
      let selectRuleArr = this.ruleOptions.filter(item => {
        return item.id == row.settlementRulesId
      })
      row.isFree = selectRuleArr[0].attribute.isFree;
      row.isFreeName = selectRuleArr[0].attribute.isFreeName;
      row.settlementRules = selectRuleArr[0].ruleName;
      row.qualityStatus = selectRuleArr[0].attribute.qualityStatus;
    },
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.attribute?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId, false, true);
    }
  },
  components: {}
}
</script>

<style lang="scss">
  .search-in-part-item {
    padding: 8px 5px 8px 0;
    overflow: hidden;
    max-width: 260px;
    p {
      line-height: 20px;
      margin: 0 16px 0 0;
      white-space: initial;
    }

    .no_empty {
      padding: 0;
      text-align: center;
      color: #999;
      font-size: 14px;
    }
  }
</style>

<style lang="scss" scoped>
input[type="number"],
.el-autocomplete {
  width: 99%;
}

.el-table {
  &::before {
    content: "";
  }
}
</style>